package com.yk._18自旋锁;

import java.util.concurrent.atomic.AtomicReference;

public class MySinpLock {
    public static void main(String[] args) {
        SinpLock sinpLock = new SinpLock();

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                sinpLock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "开始执行业务....");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "结束执行业务....");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    sinpLock.unlock();
                }

            }, "A" + i).start();
        }


    }

}

/**
 * 自旋锁
 */
class SinpLock{

    AtomicReference<Object> atomicReference = new AtomicReference<>();


    public void lock() {
        do {
            System.out.println(Thread.currentThread().getName() + "正在转圈");
        } while (!atomicReference.compareAndSet(null, Thread.currentThread().getName()));

    }

    public void unlock() {
        atomicReference.compareAndSet(Thread.currentThread().getName(), null);
    }
}
